package com.jjb.www.ui.activity;

import android.content.Intent;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.AppCompatImageView;

import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.shape.layout.ShapeLinearLayout;
import com.hjq.shape.view.ShapeButton;
import com.hjq.shape.view.ShapeTextView;
import com.jjb.www.R;
import com.jjb.www.app.AppActivity;
import com.jjb.www.http.api.AddStudyLogApi;
import com.jjb.www.http.api.AgencyListApi;
import com.jjb.www.http.api.CurriculumApi;
import com.jjb.www.http.api.CurriculumSortApi;
import com.jjb.www.http.api.VideoAddressApi;
import com.jjb.www.http.glide.GlideApp;
import com.jjb.www.http.model.HttpData;
import com.jjb.www.http.model.HttpList;
import com.jjb.www.other.AppConfig;
import com.jjb.www.ui.adapter.ExpandableListViewAdapter;
import com.jjb.www.ui.fragment.CourseListFragment;
import com.jjb.www.widget.SampleCoverVideo;
import com.shuyu.gsyvideoplayer.GSYVideoADManager;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.tencent.smtt.sdk.QbSdk;

/**
 * author : Android CRG
 * time   : 2018/10/18
 * desc   : 课程详情
 */
public class CurriculumDetitleActivity extends AppActivity implements SampleCoverVideo.OnListener {
    private ExpandableListViewAdapter adapter;//
    private ShapeLinearLayout mLlRecording;
    //证书id
    private String card_book_id = "0";
    //0全部课程 1专业课程  2公共课程
    private String status = "0";
    //1继教 2岗前
    private Integer cate = 1;
    //课程id
    private String teach_course_info_id = "0";
    //用户管理证书id
    private String certificate_id = "0";
    //结业id
    private String teach_complete_log_id = "0";
    //继教课程分类 1专业人员 2农村工匠 3特种作业
    private String sentry_parent_id = "0";
    //岗位id
    private String sentry_id = "0";
    //农村工匠 特种作业 乡村建设人才（乡村建设指导员，乡村建设工匠，传统建筑工匠） 学员id
    private String student_id;
    //视频播放id
    private String videUrlId = "";



    private AppCompatImageView mIvImg;
    /**
     * 增加视频封面
     */
    private ImageView imageView;
    private SampleCoverVideo mPlayerView;
    private FrameLayout mIvBack;
    private ShapeTextView mTvKcName;
    private ShapeTextView mTvNumber;
    private ShapeLinearLayout mLlType1;
    private ShapeLinearLayout mLlType2;
    private ExpandableListView mListview;
    private ShapeLinearLayout mLlPayView;
    private AppCompatCheckBox mCkAgree;
    private ShapeTextView mTvPrice;
    private ShapeButton mBtnPay;
    //播放最后一节
    private Integer last_course_id = 0;
    //播放最后一章
    private Integer last_chapter_id = 0;
    //课程详情
    private CurriculumApi.Bean.CourseInfoDTO courseInfo;
    //当前播放节的数据
    CurriculumApi.Bean.ListDTO.ChapterListDTO jie;
    //当前视频的播放最长时长
    private Integer videProgress = 0;
    private boolean isshiKan = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_curriculum_detitle;
    }

    @Override
    protected void initView() {
        mIvImg = findViewById(R.id.iv_img);
        mPlayerView = findViewById(R.id.detail_player);
        mIvBack = findViewById(R.id.iv_back);
        mTvKcName = findViewById(R.id.tv_kc_name);
        mTvNumber = findViewById(R.id.tv_number);
        mLlType1 = findViewById(R.id.ll_type1);
        mLlRecording = findViewById(R.id.ll_recording);
        mLlType2 = findViewById(R.id.ll_type2);
        mListview = findViewById(R.id.listview);
        mLlPayView = findViewById(R.id.ll_pay_view);
        mCkAgree = findViewById(R.id.ck_agree);
        mTvPrice = findViewById(R.id.tv_price);
        mBtnPay = findViewById(R.id.btn_pay);
        getStatusBarConfig().statusBarDarkFont(true).fitsSystemWindows(true).statusBarColor(R.color.white).init();
        setOnClickListener(mLlRecording,mIvBack);
//视频相关
        imageView = new ImageView(this);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        mPlayerView.setOnListener(this);
        resolveNormalVideoUI();
        mListview.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                adapter.setItemSel(groupPosition, childPosition);
                CurriculumApi.Bean.ListDTO.ChapterListDTO jie = (CurriculumApi.Bean.ListDTO.ChapterListDTO) adapter.getChild(groupPosition, childPosition);
                videUrlId = jie.getFile_and_text();
                getVideUrl(jie);
                return false;
            }
        });
    }
    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

    /**
     * 播放器配置
     */
    private void resolveNormalVideoUI() {
        //增加title
        mPlayerView.getTitleTextView().setVisibility(View.GONE);
        mPlayerView.getBackButton().setVisibility(View.GONE);
        mPlayerView.setReleaseWhenLossAudio(false);
        mPlayerView.setIsTouchWiget(true);
        mPlayerView.setShowPauseCover(true);
        mPlayerView.setRotateViewAuto(false);
        mPlayerView.setLockLand(true);
        mPlayerView.setShowFullAnimation(false);
        mPlayerView.setNeedLockFull(true);
    }

    /**
     * 获取视频播放地址
     */
    private void getVideUrl(CurriculumApi.Bean.ListDTO.ChapterListDTO jie) {
        EasyHttp.get(this)
                .api(new VideoAddressApi()
                        .setFile_and_text(videUrlId))
                .request(new HttpCallback<HttpList<VideoAddressApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpList<VideoAddressApi.Bean> data) {
                        if (data.getData()==null){
                            toast("获取课程失败");
                            return;
                        }
                        jie.setVideUrl(data.getData().get(0).getPlayURL());
                        mPlayerView.goneView();
                        newInitPlayer(jie);
                    }

                });
    }

    public void newInitPlayer(CurriculumApi.Bean.ListDTO.ChapterListDTO jie) {
//        mPlayerView.getCurrentPlayer().setLockLand(true);
        mPlayerView.setLearnedProgress(10);
        mPlayerView.setUpLazy("https://jjboss.oss-cn-hangzhou.aliyuncs.com/static/app/video/jjbvideo.mp4", false, null, null, null);
        mPlayerView.setVideoAllCallBack(new GSYSampleCallBack() {
            @Override
            public void onPrepared(String url, Object... objects) {
                super.onPrepared(url, objects);
            }

            //进入全屏
            @Override
            public void onEnterFullscreen(String url, Object... objects) {
                super.onEnterFullscreen(url, objects);
                mPlayerView.getCurrentPlayer().getTitleTextView().setText((String) objects[0]);
            }

            //播放完成
            @Override
            public void onAutoComplete(String url, Object... objects) {
                super.onAutoComplete(url, objects);
                initPlayer(jie);
            }

            @Override
            public void onClickStartError(String url, Object... objects) {
                super.onClickStartError(url, objects);
            }

            //退出全屏
            @Override
            public void onQuitFullscreen(String url, Object... objects) {
                super.onQuitFullscreen(url, objects);
                //退出全屏逻辑
                if (mPlayerView.isIfCurrentIsFullscreen()) {
                    mPlayerView.onBackFullscreen();
                }

            }
        });
        mPlayerView.setGSYVideoProgressListener(new GSYVideoProgressListener() {
            @Override
            public void onProgress(int progress, int secProgress, int currentPosition, int duration) {
            }


        });

        //设置返回按键功能
        mPlayerView.getBackButton().setOnClickListener(v -> onBackPressed());
        //设置全屏按键功能
        mPlayerView.getFullscreenButton().setOnClickListener(v -> resolveFullBtn(mPlayerView));
        mPlayerView.setSeekOnStart(jie.getSecond() * 1000L);
        mPlayerView.getCurrentPlayer().startPlayLogic();
    }

    private void initPlayer(CurriculumApi.Bean.ListDTO.ChapterListDTO jie) {
        isshiKan = false;
        mPlayerView.setLearnedProgress(100);
//        mPlayerView.getCurrentPlayer().setLockLand(false);
        videProgress = 0;
        mPlayerView.setUpLazy(jie.getVideUrl(), false, null, null, null);
        mPlayerView.setVideoAllCallBack(new GSYSampleCallBack() {
            @Override
            public void onPrepared(String url, Object... objects) {
                super.onPrepared(url, objects);
            }

            @Override
            public void onClickStartIcon(String url, Object... objects) {
                super.onClickStartIcon(url, objects);
                mPlayerView.setTag();
            }

            //进入全屏
            @Override
            public void onEnterFullscreen(String url, Object... objects) {
                super.onEnterFullscreen(url, objects);
                mPlayerView.getCurrentPlayer().getTitleTextView().setText((String) objects[0]);
            }

            //播放完成
            @Override
            public void onAutoComplete(String url, Object... objects) {
                super.onAutoComplete(url, objects);

            }

            @Override
            public void onClickStartError(String url, Object... objects) {
                super.onClickStartError(url, objects);
            }

            //退出全屏
            @Override
            public void onQuitFullscreen(String url, Object... objects) {
                super.onQuitFullscreen(url, objects);
                //退出全屏逻辑
                if (mPlayerView.isIfCurrentIsFullscreen()) {
                    mPlayerView.onBackFullscreen();
                }

            }
        });
        mPlayerView.setGSYVideoProgressListener(new GSYVideoProgressListener() {
            private int timeFlag = jie.getSecond() + 10;

            @Override
            public void onProgress(int progress, int secProgress, int currentPosition, int duration) {
                int currentSecond = currentPosition / 1000;

                if (currentSecond > videProgress) {
                    videProgress = currentSecond;
                }
                if (currentSecond > timeFlag) {
                    timeFlag += 10;
                    int baifen = (currentSecond / jie.getDuration_num()) * 100;
//                    mPlayTime = timeFlag;
                    recordTime(jie.getId(), jie.getTeach_course_id(), jie.getTeach_course_info_id(), jie.getNumber(), baifen, timeFlag);
                }
                //未支付
                if (courseInfo.getPay_status() == 0) {
                    //试看提示用户去购买课程
                    if (currentSecond >= courseInfo.getSee_second()) {
                        mPlayerView.getCurrentPlayer().onVideoReset();
                        if (mPlayerView.isIfCurrentIsFullscreen()) {
                            mPlayerView.onBackFullscreen();
                        }
                        mPlayerView.setFlag(true);
                    } else {
//                        mPlayerView.setFlag(false);
                    }
                }
            }


        });

        //设置返回按键功能
        mPlayerView.getBackButton().setOnClickListener(v -> onBackPressed());
        //设置全屏按键功能
        mPlayerView.getFullscreenButton().setOnClickListener(v -> resolveFullBtn(mPlayerView));
        mPlayerView.setSeekOnStart(jie.getSecond() * 1000L);
        if (courseInfo.getPay_status() == 0) {
            //试看提示用户去购买课程
            if (courseInfo.getSee_second()>0) {
                isshiKan = true;
            } else {
                isshiKan = false;
            }
        }

        if (isshiKan){
            mPlayerView.getCurrentPlayer().onVideoReset();
            if (mPlayerView.isIfCurrentIsFullscreen()) {
                mPlayerView.onBackFullscreen();
            }
            mPlayerView.setFlag(false);
            isshiKan = false;
        }else {
            mPlayerView.getCurrentPlayer().startPlayLogic();
        }

    }

    /**
     * @param id                   课程章节小节id
     * @param teach_course_id      课程章节id
     * @param teach_course_info_id 课程概述id
     * @param number               小节编号
     * @param baifen               进度 例如 （10 20） 100代表已看完
     * @param timeFlag             观看秒数
     */
    private void recordTime(Integer id, Integer teach_course_id, Integer teach_course_info_id, String number, int baifen, int timeFlag) {
        EasyHttp.get(this)
                .api(new AddStudyLogApi()
                        .setBaifen(baifen)
                        .setTeach_course_id(teach_course_id)
                        .setTeach_chapter_id(id)
                        .setTeach_course_info_id(teach_course_info_id)
                        .setTeach_complete_log_id(0)
                        .setNumber(number)
                        .setSecond(timeFlag)
                        .setCard_book_id(courseInfo.getCard_book_id())
                        .setCate(cate)
                        .setCertificate_id(certificate_id)
                        .setSdk_open("0")
                        .setSentry_id(0)
                        .setSentry_parent_id(courseInfo.getSentry_parent_id())
                        .setStudent_id(courseInfo.getStudent_id())
                )
                .request(new HttpCallback<HttpData<AddStudyLogApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<AddStudyLogApi.Bean> data) {

                    }

                });
    }

    /**
     * 全屏幕按键处理
     */
    private void resolveFullBtn(final StandardGSYVideoPlayer standardGSYVideoPlayer) {
        standardGSYVideoPlayer.startWindowFullscreen(this, false, true);
    }

    @Override
    protected void initData() {
        card_book_id = getString("card_book_id");
        status = getString("status");
        cate = getInt("cate");
        teach_course_info_id = getString("teach_course_info_id");
        certificate_id = getString("certificate_id");
        teach_complete_log_id = getString("teach_complete_log_id");
        sentry_parent_id = getString("sentry_parent_id");
        sentry_id = getString("sentry_id");
        student_id = AppConfig.getInstance().getUserBean().getUser().getId() + "";
        getDetitle();
    }

    @Override
    public void onClick(View view) {
        if (view == mLlRecording) {
            //学时记录
//            Intent intent = new Intent();
//            intent.putExtra("id_card",sdkInfoDTO.getId_card()+"");
//            intent.putExtra("planCode",sdkInfoDTO.getPlanCode()+"");
//            intent.putExtra("trainPostCode",sdkInfoDTO.getTrainPostCode()+"");
//            intent.setClass(getContext(),VerificationRecordActivity.class);
//            startActivity(VerificationRecordActivity.class);
        }else if (view==mIvBack){
            finish();
        }
    }

    //课程详情
    private void getDetitle() {
        EasyHttp.get(this)
                .api(new CurriculumApi()
                        .setCard_book_id(card_book_id)
                        .setStatus(status)
                        .setCate(cate+"")
                        .setTeach_course_info_id(teach_course_info_id)
                        .setCertificate_id(certificate_id)
                        .setTeach_complete_log_id(teach_complete_log_id)
                        .setSentry_parent_id(sentry_parent_id)
                        .setSentry_id(sentry_id)
                        .setStudent_id(student_id)
                )
                .request(new HttpCallback<HttpData<CurriculumApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<CurriculumApi.Bean> data) {
                        courseInfo = data.getData().getCourse_info();
                        mTvKcName.setText(courseInfo.getTitle());
                        mTvNumber.setText(courseInfo.getChapter_num_desc());
                        mTvPrice.setText(courseInfo.getAndroid_money());
                        if ("0.00".equals(courseInfo.getAndroid_money())) {
                            mLlPayView.setVisibility(View.GONE);
                        } else {
                            mLlPayView.setVisibility(View.VISIBLE);
                        }
                        for (CurriculumApi.Bean.ListDTO listDTO :data.getData().getList()) {
                            listDTO.setIsfree(true);
                        }
                        adapter = new ExpandableListViewAdapter(getContext(), data.getData().getList(), new ExpandableListViewAdapter.OnListener() {
                            @Override
                            public void onSelected(int position) {

                            }
                        });
                        mListview.setAdapter(adapter);
                        for (int i = 0; i < data.getData().getList().size(); i++) {
                            if (data.getData().getList().get(i).getId().equals(data.getData().getCourse_info().getLast_course_id())) {
                                last_chapter_id = i;
                                for (int a = 0; a < data.getData().getList().get(i).getChapter_list().size(); a++) {
                                    if (data.getData().getList().get(i).getChapter_list().get(a).getId().equals(data.getData().getCourse_info().getLast_chapter_id())) {
                                        last_course_id = a;
                                        jie = data.getData().getList().get(i).getChapter_list().get(a);
                                        videUrlId = data.getData().getList().get(i).getChapter_list().get(a).getFile_and_text();
                                    }
                                }
                            }
                        }
                        adapter.setItemSel(last_chapter_id, last_course_id);
                        mListview.expandGroup(last_chapter_id);
                        if ("".equals(videUrlId)){
                            return;
                        }
                        getVideUrl(jie);
                    }
                });
    }

    @Override
    public void onBackPressed() {
        if (GSYVideoADManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPlayerView.onVideoPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPlayerView.onVideoResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPlayerView.release();
        GSYVideoManager.releaseAllVideos();
    }

    @Override
    public void onBuyCourse() {

    }

    @Override
    public void onIsAudition() {

    }
}